package com.xxl.servlet;

import com.xxl.bean.Student;
import com.xxl.services.StudentService;
import com.xxl.services.impl.StudentServiceImpl;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@WebServlet("*.student")
public class StudentServlet extends HttpServlet{
    StudentService scService = new StudentServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        ServletContext servletContext = req.getServletContext();
        String path = (String) servletContext.getAttribute("path");
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        String servletPath = req.getServletPath();
        String reqName = servletPath.split("\\.")[0].split("/")[1];
        if ("addOrUpdate".equals(reqName)){
            String studentId = req.getParameter("studentId");
            String studentName = req.getParameter("studentName");
            String classesName = req.getParameter("classesName");
            scService.addOrUpdate(studentId,studentName,classesName);
        }else if ("delete".equals(reqName)){
            String vs = req.getParameter("vs");
            String studentId = vs.split("Student\\{studentId=")[1].split(",")[0];
            boolean flag = scService.delete(studentId);
            if (flag){
                resp.getWriter().println("删除成功");
            }else {
                resp.getWriter().println("删除失败");
            }
        }
        List<Student> list = new ArrayList<>();
        try {
            scService.listAddStudent(list);
        } catch (SQLException throwables) {
            System.out.println(throwables);
        }
        req.setAttribute("student",list);
        req.getRequestDispatcher(path).forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)  throws IOException, ServletException {
            doGet(req,resp);
    }

    public static String getUUID(){
        UUID uuid= UUID.randomUUID();
        String str = uuid.toString();
        return str.replace("-", "");
    }


}
